package common.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.springframework.context.annotation.Scope;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import com.dao.JdbcDAO;
import common.pojo.HotelPic;

@Scope("prototype")
@Repository
public class HotelPicDAO extends JdbcDAO {
	
	@SuppressWarnings("unchecked")
	public List<HotelPic> findList(String where, int start, int limit,
			String orderbys) {

		String sql = "SELECT id,picName,picUrl,sort FROM "
				+ "(SELECT *, ROW_NUMBER() OVER (ORDER BY  " + orderbys
				+ ") as rowNum FROM hotelPic " + where + ")" + " AS T "
				+ "WHERE T.RowNum>" + start + "and T.RowNum<="
				+ (start + limit);
		return getList(sql, null, new HotelPicMapper());
	}

	@SuppressWarnings("unchecked")
	public List<HotelPic> findList() {

		String sql = "SELECT id,picName,picUrl,sort FROM hotelPic";
		return getList(sql, null, new HotelPicMapper());
	}

	public int getCount(String where) {
		return getCount("select count(*) from hotelPic " + where, null);
	}

	public HotelPic findInfoById(int id) {

		String sql = "select id,picName,picUrl,sort from hotelPic where id ="
				+ id;
		return (HotelPic) getObject(sql, null, new HotelPicMapper());

	}

	public boolean update(HotelPic hotelPic) {
		String sql = "update hotelPic set picName=?,picUrl=?,sort=? where id=?";
		update(sql, new Object[] { hotelPic.getPicName(), hotelPic.getPicUrl(),
				hotelPic.getSort(), hotelPic.getId() });
		return true;
	}

	public boolean delete(int id) {
		String sql = "delete from hotelPic where id = " + id;
		delete(sql);
		return true;
	}

	public void save(HotelPic hotelPic) {
		String sql = "insert into hotelPic values(?,?,?)";
		save(sql, new Object[] { hotelPic.getPicName(), hotelPic.getPicUrl(),
				hotelPic.getSort() });
	}

	private static final class HotelPicMapper implements RowMapper {

		public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
			HotelPic hotelPic = new HotelPic();
			hotelPic.setId(rs.getInt(1));
			hotelPic.setPicName(rs.getString(2));
			hotelPic.setPicUrl(rs.getString(3));
			hotelPic.setSort(rs.getInt(4));

			return hotelPic;
		}
	}

}
